﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hands.Unit;
using System.Web;

namespace Hands.CSRF.Defense
{
    public static class CookieHandler
    {
        private static readonly string cookieName = null;

        private static HashSet<string> cookieValues = new HashSet<string>();

        static CookieHandler()
        {
            cookieName = UUID.create();
        }

        internal static string CookieName
        {
            get
            {
                return cookieName;
            }
        }

        internal static bool isLegal(string cookieValue)
        {
            lock (cookieValues)
            {
                if (cookieValues.Contains(cookieValue))
                {
                    cookieValues.Remove(cookieValue);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        private static string CookieValue
        {
            get
            {
                string value = UUID.create();
                lock (cookieValues)
                {
                    cookieValues.Add(value);
                }
                return value;
            }
        }

        private static object mutex = new object();

        public static HttpCookie create(string domain)
        {
            lock (mutex)
            {
                HttpCookie cookie = new HttpCookie(CookieName, CookieValue);
                cookie.HttpOnly = true;
                cookie.Domain = domain;
                return cookie;
            }
        }
    }
}
